﻿
//this function updates the server side with each cell click to support "Ask the Crowd" DB
function updateServlet(update,row,col){
	var servlet = "http://gilivaturitest.appspot.com/totoChartsUpdate";  
	var req = servlet + "?" +update+col+row;  //compiling the request

	addrequest(req); 
}

// a help function to support updateServlet
function addrequest(req) {
	try {                                     //create a request for netscape, mozilla, opera, etc.
		request = new XMLHttpRequest();
	}catch (e) {

		try {                                 //create a request for internet explorer
			request = new ActiveXObject("Microsoft.XMLHTTP");
		}catch (e) {  
			alert("XMLHttpRequest error: " + e);
		}
	}

	request.open("GET", req, true);       //prepare the request
	request.send(null);                       //send it
	return request;                           //return the request
}

/********** appengine part ****************************/



// a special request bybasing cache of browser in prder to update at will.
function makeCachedRequest(url, response, params, refreshInterval) {
	var ts = new Date().getTime();
	var sep = "?";
	if (refreshInterval && refreshInterval > 0) {
		ts = Math.floor(ts / (refreshInterval * 1000));
	}
	if (url.indexOf("?") > -1) {
		sep = "&";
	}
	url = [ url, sep, "nocache=", ts ].join("");
	gadgets.io.makeRequest(url, response, params);
}



/* 	getting data into the state: 	
			(type==0)-> games			 
			(type==1)-> results			
			(type==2)-> recommendations	 
			(type==3)-> returns the time and date string */

/* this function turns to 5 different servlet requests to obtain 4 types of data:
	type == 0 --> matches
	type == 1 --> results
	type == 2 --> recommendations
	type == 3 --> current time from appengine
	type == 4 --> raw statistics 
*/
function RefreshData(type){
	var str;
	var	time;		
	function response(obj) {  
		//obj.text contains the text of the page that was requested  
		str = obj.text;
		if(type==0){
			wave.getState().submitDelta({ "GamesStr" : str});
		}
		if(type==1){
			checkResults (str);
		}
		if(type==2){
			wave.getState().submitDelta({ "RecStr" : str});
		}
		if(type==3){
			wave.getState().submitDelta({ "TimeStr" : str});
		}
		if(type==4){
			wave.getState().submitDelta({ "StatLinksStr" : str});
		}		
	}

	var params = {};  
	params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.TEXT;  
	var url;
	if(type==0){
		url = "http://gilivaturitest.appspot.com/gadgetRequestFormServlet"; 
	}
	if(type==1){
		url = "http://gilivaturitest.appspot.com/gadgetRequestResultsServlet";
	}
	if(type==2){
		url = "http://gilivaturitest.appspot.com/gadgetRequestRecServlet";
	}
	if(type==3){
		url = "http://gilivaturitest.appspot.com/gadgetRequestTimeServlet";
	}
	if(type==4){
		url = "http://gilivaturitest.appspot.com/gadgetRequestStatServlet";
	}
	makeCachedRequest(url, response, params,60); // 60 seconds till next cache refresh
}



//this is an ajax function that accesses the servlet that holds the populairty clicks, 
//gets the information and invokes google visualization function
function drawChart(el){   
	var str;
	var	time;
	function response(obj) {  
		//obj.text contains the text of the page that was requested  
		str = obj.text;
		var results= {};
		results=str.split("#");
		var x=parseInt(results[game_num*3]);
		var y=parseInt(results[(game_num*3)+1]);
		var z=parseInt(results[(game_num*3)+2]);
		drawVisualization(x,y,z,game_num);
	}
	
	var game_id = el.id;
  var game_num = parseInt(game_id.substr(5));

	var params = {}; 
	params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.TEXT;
	var url="http://gilivaturitest.appspot.com/gadgetRequestTotoChart";
	makeCachedRequest(url, response, params,5); // 5 seconds till next cache refresh
}

/*** POST FUNCTIONS  - This section includes functions that support sending POST requests to the server****/

/*This function gets an HTML elemnt. It creates a new IFrame within it, and returns it*/  
function IFrame(parentElement)
{
   // Create the iframe which will be returned
   var iframe = document.createElement("iframe");

   // If no parent element is specified then use body as the parent element
   if(parentElement == null)
      parentElement = document.body;

   // This is necessary in order to initialize the document inside the iframe
   parentElement.appendChild(iframe);

   // Initiate the iframe's document to null
   iframe.doc = null;

   // Depending on browser platform get the iframe's document, this is only
   // available if the iframe has already been appended to an element which
   // has been added to the document
   if(iframe.contentDocument){
      // Firefox, Opera
      iframe.doc = iframe.contentDocument;
      }
   else if(iframe.contentWindow){
      // Internet Explorer
      iframe.doc = iframe.contentWindow.document;
      }
   else if(iframe.document) {
      // Others?
      iframe.doc = iframe.document;
      }

   // If we did not succeed in finding the document then throw an exception
   if(iframe.doc == null)
      jAlert('Document not found, append the parent element to the DOM before creating the IFrame','IFrame Error');

   // Create the script inside the iframe's document
   iframe.doc.open();
   iframe.doc.close();

   // Return the iframe, now with an extra property iframe.doc containing the
   // iframe's document
   return iframe;
}

/* This funcion gets a url path, parameters and GET\POST method - and sends the request to the server, using a virtual form submit*/ 
function post_to_url(path, params, method) {
    method = method || "post"; // Set method to POST by default, if not specified.

    var canvas = document.getElementById("canvas");
    var iframe = new IFrame(canvas);

    var form = iframe.doc.createElement("form");
    form.setAttribute("method", method);
    form.setAttribute("action", path);

    for(var key in params) {
        var hiddenField = iframe.doc.createElement("input");
        hiddenField.setAttribute("type", "hidden");
        hiddenField.setAttribute("name", key);
        hiddenField.setAttribute("value", params[key]);

        form.appendChild(hiddenField);
    }   
    iframe.doc.body.appendChild(form);   
    form.submit();

}

// this function gets last week parameters and saves the last week toto form in the DB of the server
function post(gamesString,formFillout,crrectResults,cost,prize,numberOfCorrectGuesses,idiotID,hotID){
    var url= "https://gilivaturitest.appspot.com/totoOldFormStorage"; //servlet address
    var dateFromState=wave.getState().get("cellClickUpperLimit"); //get the date from last week.
	var waveID=wave.getState().get( "waveID" ); //get the waveID from state.
	var param=[];
	
	// build the parameter array for the post_to_url function
	param['lorem']=gamesString+'*'+formFillout+'*'+crrectResults+'*'+cost+'*'+prize+'*'+numberOfCorrectGuesses+'*'+idiotID+'*'+hotID+'*'+"End";   //params is an Array of key's and their values
	param['ID']=waveID;
	param['date']=dateFromState;
    
    var meth="POST";                //Use POST method

	post_to_url(url,param,meth);
            
}
/******** END OF POST FUNCTIONS*************************************************************************************************8****/

//this function should be run only on the first init. it will create a unique waveID that is later used for wave-server communication
function getWaveIDfromDB(){
	var str;		
	function response(obj) {  
		//obj.text contains the text of the page that was requested  
		str = obj.text;
		wave.getState().submitDelta({ "waveID" : str});
	}

	var params = {};  
	params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.TEXT;  
	var url="http://gilivaturitest.appspot.com/gadgetRequestWaveID";
	makeCachedRequest(url, response, params,60); // 60 seconds till next cache refresh

}
//This function updates the "Team History" page with past week form and details - according to the Time Stamp parameter received
function getOldForm(appEngineCellUpperLimit){
var str;		
	function response(obj) {  
		//obj.text contains the text of the page that was requested  
		str = obj.text;
		var appEngineArray = str.split("*");
		
		form_date=new Date(parseInt(appEngineCellUpperLimit));		
		document.getElementById("table_top_past_form").innerHTML= (form_date.toLocaleDateString());
				
		RefreshLastWeekGames(appEngineArray[0]); //update the main table with the matches
		RefreshLastWeekStatistics(appEngineArray[3],appEngineArray[4],appEngineArray[5]); //updates the cost,prize,num_of_correct_guesses
		RefreshLastWeekIdiot(appEngineArray[6],appEngineArray[7]);       //update the Idiot information (name&pic)
		RefreshLastWeekCells(eval( "(" + appEngineArray[2] + ")" ));     //update the table cells colors
		
		
	}

	var params = {};
	var waveID=wave.getState().get( "waveID" );	
	params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.TEXT;  
	var url="http://gilivaturitest.appspot.com/gadgetRequestOldForm?"+waveID+"~"+appEngineCellUpperLimit;
	makeCachedRequest(url, response, params,60); // 60 seconds till next cache refresh
}